package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
@Slf4j
public class RecommendUserImpl implements RecommendUserApi {


    @Autowired
    private MongoTemplate mongoTemplate;



    @Override
    public RecommendUser findMaxScore(Long loginUserId) {

        //构造查询条件 根据登录用户id 缘分降序排序
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(loginUserId));
        query.with(Sort.by(Sort.Direction.DESC,"score"));
        return mongoTemplate.findOne(query,RecommendUser.class);
    }



    /**
     * 根据当前用户id和佳人用户id查询RecommendUser
     *
     * @param personUserId
     * @param userId
     * @return
     */
    @Override
    public RecommendUser findByUserId(Long personUserId, Long userId) {
        //构建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(personUserId)
                .and("toUserId").is(userId)
        );
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        //如果recommendUser为空 设置下假数据
        if(recommendUser == null){
            recommendUser = new RecommendUser();
            recommendUser.setScore(88d);//缘分值
            recommendUser.setUserId(personUserId);//佳人用户id
            recommendUser.setToUserId(userId);//当前用户id
        }
        return recommendUser;
    }

    /**
     * 分页查询推荐用户列表
     *
     * @param loginUserId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult<RecommendUser> findPageRecommendUser(Long loginUserId, Long page, Long pagesize) {
        long start = (page-1)*pagesize;
        //查询总记录数
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(loginUserId));
        long count = mongoTemplate.count(query, RecommendUser.class);
        //每页显示的数据
        query.skip(start).limit(pagesize.intValue());
        //根据userId排序
        query.with(Sort.by(Sort.Direction.ASC,"userId"));
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        return new PageResult<>(page,pagesize,count,recommendUserList);
    }


    /**
     * 根据当前登录用户id查询RecommendUser表随机查10条数据
     *
     * @param loginUserId
     * @return
     */
    @Override
    public List<RecommendUser> findCards(Long loginUserId) {
        log.debug("******************当前用户id{}*******************",loginUserId);
        //1根据当前用户id查询user_like 喜欢和不喜欢用户ids

        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(loginUserId));
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        log.debug("******************userLikeList{}*******************",userLikeList);
        //2根据当前用户id 排除user_like表中（喜欢和不喜欢用户ids） 到RecommendUser表随机查询10条记录
        List<Long> isLikeUserIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userLikeList)){
            isLikeUserIds = userLikeList.stream().map(UserLike::getUserId).collect(Collectors.toList());
        }
        log.debug("******************isLikeUserIds{}*******************",isLikeUserIds);
        //参数2：Aggregation.match():匹配条件对象 （等于 in not in 等都可以）
        //参数3：随机几条数据 Aggregation.sample(10)
        Criteria criteria = Criteria.where("toUserId").is(loginUserId).and("userId").nin(isLikeUserIds);
        //2.1随机查询api方法
        TypedAggregation<RecommendUser> typedAggregation =
                TypedAggregation.newAggregation(RecommendUser.class, Aggregation.match(criteria),Aggregation.sample(10));
        AggregationResults<RecommendUser> recommendUser = mongoTemplate.aggregate(typedAggregation, RecommendUser.class);
        //参数1：随机查询条件对象  参数2：随机查询实体对象类
        return recommendUser.getMappedResults();
    }

}
